/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */
package com.ecarx.systemui.plugin.ui.statusbar

import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.util.AttributeSet
import androidx.core.content.res.ResourcesCompat
import com.ecarx.systemui.plugin.R
import com.ecarx.systemui.plugin.ui.custom.SystemBarButton
import com.ecarx.systemui.plugin.utils.LogUtils

class UserView : SystemBarButton {

    constructor(context: Context?) : this(context!!, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context!!, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context!!,
        attrs,
        defStyleAttr
    )

    override fun getContentDescriptionString(): String {
        return "UserView"
    }

    override fun initView() {
        super.initView()

        setImageDrawable(
            ResourcesCompat
                .getDrawable(
                    resources,
                    R.drawable.selector_status_bar_user,
                    context.theme
                )
        )

        setOnClickListener {
            showDialog()
        }
    }

    private fun showDialog() {
        LogUtils.d(TAG, "show user info dialog")
        try {
            val testIntent = Intent()
            testIntent.putExtra("time", System.currentTimeMillis())
            testIntent.component = ComponentName(
                "ecarx.membercenter",
                "com.ecarx.membercenter.main.preference.PreferenceDialogService"
            )
            val componentName: ComponentName? =
                context.startForegroundService(testIntent)
            LogUtils.d(TAG, "componentName$componentName")
            if (componentName == null) {
                val component =
                    ComponentName("ecarx.membercenter", "ecarx.membercenter.stub.EntryActivity")
                val intent = Intent()
                intent.putExtra("EntryCode", 1)
                intent.component = component
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                try {
                    val pendingIntent: PendingIntent =
                        PendingIntent.getActivity(context, 0, intent, 0)
                    pendingIntent.send()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        } catch (throwable: Throwable) {
            LogUtils.e(TAG, throwable.toString())
        }
    }

    companion object {
        private const val TAG = "UserView"
    }
}